<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller {

	function __construct() {
		parent::__construct ();
		$this->load->helper('url');
		//$this->load->driver('cache');  
		
		$this->load->model('Place_model');
		$this->load->model('User_model');//Admin model
	}
	function getIP() {
		if (isset ( $_SERVER ["HTTP_X_FORWARDED_FOR"] )) 

		{
	
			//reg ex pattern
	
			$pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
			if(preg_match( pattern, $_SERVER ["HTTP_X_FORWARDED_FOR"] )) 
			{
				$userIP = $_SERVER ["HTTP_X_FORWARDED_FOR"];
			} 
			else 
			{
				$userIP = $_SERVER ["REMOTE_ADDR"];
			}
		} 		
		else 
		{
			$userIP = $_SERVER ["REMOTE_ADDR"];
		}
		return  $userIP;
	}
	function ShowGoogleMap()
	{
		$api_key='LOCAL_KEY';
		$width=555;
		$height=280;
		$zoom=8;
		
		$user_ip = $this->getIP();
		$user_ip="101.99.8.18";
		$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip) or die('Error getting meta tags');
		$city = $meta_tags['city'];
		$state = $meta_tags['regioncode'];
		$country = $meta_tags['fips104'];
		$lat = $meta_tags['latitude'];
		$long = $meta_tags['longitude'];
		$address = urlencode($city . ', ' . $state . ', ' . $country);
		$img_source = 'http://maps.google.com/staticmap?key=' . $api_key . '&size=' . $width . 'x' . $height . '&markers=' . $lat . ',' . $long . '&zoom=' . $zoom;
	
		echo $img_source;
	}
	
	function index()
	{
		/*------------Lay danh sach cac ban ghi de hien thi-------------*/
	/* 	if(isset($_POST['page']))
			$page =$_POST['page'] ; // get the requested page
		else $page=1;
		if(isset($_POST['rows']))
			$limit=$_POST['rows'];// get how many rows we want to have into the grid
		else $limit = 1;
		if(isset($_POST['sidx']))
			$sidx=$_POST['sidx'];// get index row - i.e. user click to sort
		else $sidx = 'id';
		if(!$sidx) $sidx ='id';
		if(isset($_POST['sord']))
			$sord=$_POST['sord'];// get the direction
		else $sord= 'desc'; 
		$total_pages=0;
		$where='';
		$by=$sord;
		$order=$sidx;
		$count = count($this->Place_model->fetch("id", $where, "", ""));
		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else { $total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
		*/
		$where='';
		$start=0;
		$limit=100;
		$sord= 'desc';
		$sidx='id';
		$select = "id, lat, lng,title,price,typeid,description,img1,createddate";
		$data['houseArray'] = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
			
		/* $i=0;
		foreach($result as $userArray)
		{
			$responce->rows[$i]['id']=$userArray->id;
			$responce->rows[$i]['cell']=array($userArray->id,$userArray->lat,$userArray->lng,$userArray->title,$userArray->price,$userArray->typeid);
			$i++;
		}
		echo json_encode($responce); */
		
		$this->load->view('home/index/index',$data);
	}
	function person()
	{
		$this->load->view('home/person/person');
	}
	function notFound()
	{
		echo 'File not found';
	}
	function detail($placeId)
	{
		//$this->output->cache(1);
		$start=0;
		$limit=1;
		$sidx='';
		$sord='';
		$id=(int)$placeId;
		$where="id =$id";
		$select = "id,title, createddate, img1, img2,img3, img4,img5,img6, img7,img8, img9,img10,img11,img12, description,typeid,price,lat,lng";
		$data['houseArray'] = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
		$this->load->view('home/place/viewDetail',$data);
	}
	
    function postInfo()
	{
		$this->load->view('home/person/postInfo');
	}
    function place()
	{
		$this->load->view('home/place/context');
	}
    //Get all record of place
	public function getAll()
	{
		/*------------------------------------------------------------------------------*/
		if(isset($_POST['page']))
			$page =$_POST['page'] ; // get the requested page
		else $page=1;
		if(isset($_POST['rows']))
			$limit=$_POST['rows'];// get how many rows we want to have into the grid
		else $limit = 1;
		if(isset($_POST['sidx']))
			$sidx=$_POST['sidx'];// get index row - i.e. user click to sort
		else $sidx = 'id';
		if(!$sidx) $sidx ='id';
		if(isset($_POST['sord']))
			$sord=$_POST['sord'];// get the direction
		else $sord= 'desc';
		$total_pages=0;
		$where='';
		$by=$sord;
		$order=$sidx;	
		$count = count($this->Place_model->fetch("id", $where, "", ""));
		if( $count >0 ) {
			$total_pages = ceil($count/$limit);
		} else { $total_pages = 0;
		}
		if ($page > $total_pages) $page=$total_pages;
		$start = $limit*$page - $limit; // do not put $limit*($page - 1)
		
		$select = "id, lat, lng,title,price,typeid,sqft";
		$result = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
		 
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records = $count;
		$i=0;
		foreach($result as $userArray)
		{
			$responce->rows[$i]['id']=$userArray->id;
			$responce->rows[$i]['cell']=array($userArray->id,$userArray->lat,$userArray->lng,$userArray->title,$userArray->price,$userArray->typeid,$userArray->sqft);
			$i++;
		}
		echo json_encode($responce);
	}
	
	/*---------------------Bat dau Xem 1 ban ghi--------------------------*/
	public function getOnePlace()
	{
		if(isset($_POST['id']))
			$id =(int)$_POST['id'] ; // get use_id
		else $id=-1;
		$start=0;
		$limit=1;
		$sidx='';
		$sord='';
		$where="id =$id";
		$select = "id,title, createddate, img1, img2,img3, img4,img5,img6, img7,img8, img9,img10,img11,img12, description,typeid,price,sqft,catid";
		$result = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
		$i=0;
		
		foreach($result as $userArray)
		{
			//$as->message='<div style="margin-top: 8px; background: #FFF; padding: 5px;-moz-box-shadow: inset -5px -5px 5px #888;-webkit-box-shadow: inset -5px -5px 5px #888;box-shadow: inset -5px -5px 5px #888;-moz-border-radius: 10px;border-radius: 10px;">'
			$message='<div class="form-panel-auto-dialog" ">'
			.'<table >'
			.'<tr>'
			.'<td style="width:101px;height: 76px;overflow:hidden;">';
			if($userArray->img1!=null)
			{
				$message=$message.'<img valign="top" style="cursor:pointer" onclick="resizeImg();"onmousemove="showTxt();" src="'.base_url().'themes/home/uploads/'.$userArray->img1.'" width="101px" height="76" alt="" />';
			}else
			{
				$message=$message.'<img valign="top" style="cursor:pointer" onclick="resizeImg();"onmousemove="showTxt();" src="'.base_url().'themes/home/images/demohousesmall.gif" width="101px" height="76" alt="" />';
			}	
			$message=$message.'</td>'
			.'<td onmousemove="hideTxt();" ><div><a href="'.base_url().'index/detail/'.$userArray->id.'">'.$userArray->title.'</a></div>'
			
			.'<ul style="float:left;list-style-type:none;margin: 4px;padding: 0px;">'
			.'<li>Nhu cầu: '.$this->findCatName($userArray->catid).'</li>'
			.'<li>Giá bán: '.number_format($userArray->price,0).' (VND) </li>'
			.'<li>Điện thoại:</li>'
			.'</ul>'
			.'<ul style="float:left;list-style-type:none;margin: 4px;padding: 0px;">'
			.'<li>Diện tích: '.$userArray->sqft.'m2</li>'
			.'<li>Số tầng:</li>'
			.'<li>Số phòng:</li>'
			.'</ul>'
			.'<ul style="float:left;list-style-type:none;margin: 4px;padding: 0px;">'
			//.'<li><a href="javascript:postwith(\''.base_url().'index/detail/\',{id:'.$userArray->id.'})">Chi tiết</a></li>'
			.'<li><a href="'.base_url().'index/detail/'.$userArray->id.'">Chi tiết</a></li>'
			.'</ul>'
			
			.'</td>'
			.'</tr>'
			.'<tr>'
			.'<td colspan="3" style="margin:0;padding:0">'
			.'<div id="slidingDiv" style="margin:0;padding:0"  >'
			.'<table >'
			.'<tr valign="top">'
			.'<td style="width:101px;height:192;overflow:hidden;" >';
			if($userArray->img1!=null)
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img1.'" class="subimg" alt=""/>'
				.'</div>';
			}else
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/images/demohousesmall.gif" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img2!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img2.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img3!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img3.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img4!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img4.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img5!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img5.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img6!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img6.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img7!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img7.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img8!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img8.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img9!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img9.'" class="subimg" alt=""/>'
				.'</div>';
			}
			if($userArray->img10!='')
			{
				$message=$message.'<div class="divimg">'
				.'<img onmousemove="changeImg(this)" src="'.base_url().'themes/home/uploads/'.$userArray->img10.'" class="subimg" alt=""/>'
				.'</div>';
			}
			//<a href="javascript:postwith('post.aspx',{user:'peter',cc:'aus'})">click</a>
			//$.post("test.php", {'choices[]': ["Jon", "Susan"] });
			$message=$message.'<div style="width:100px;float:left;text-align:center">'
				//.'<a href="javascript:postwith(\''.base_url().'index/detail/\',{id:'.$userArray->id.'})">Chi tiết</a>'
			    .'<a href="'.base_url().'index/detail/'.$userArray->id.'">Chi tiết</a>'
				.'</div>';
			
			$message=$message.'</td>'
			.'<td>'
			.'<div style="width:400px;height: 300px;overflow:hidden;border:1px solid #ccc">';
			if($userArray->img1!=null)
			{
				$message=$message.'<img  id="largimg" src="'.base_url().'themes/home/uploads/'.$userArray->img1.'" />';
			}else
			{
				$message=$message.'<img  id="largimg" src="'.base_url().'themes/home/images/demohouse.gif" />';
			}
			$message=$message.'</div>'
			.'</td>'
			.'</tr>'
			.'</table>'
			.'</div>'
			.'</td>	'
			.'</tr>	'
			.'</table>'
			.'</table></div></div>';
			

			$responce->rows[$i]['id']=$userArray->id;
			$responce->rows[$i]['tieude']=$userArray->title;
			//$responce->rows[$i]['ngaydang']=date("d/m/Y",$userArray->createddate);
			$responce->rows[$i]['img1']=$userArray->img1;
			$responce->rows[$i]['img2']=$userArray->img2;
			$responce->rows[$i]['img3']=$userArray->img3;
			$responce->rows[$i]['img4']=$userArray->img4;
			$responce->rows[$i]['img5']=$userArray->img5;
			$responce->rows[$i]['mota']=$userArray->description;
			$responce->rows[$i]['loai']=$userArray->typeid;
			$responce->rows[$i]['gia']=number_format($userArray->price,0);
			$i++;
			//echo json_encode($responce);
			//$dp->msg=$as;	
			$as->message=$message;
			echo json_encode($as);
			
		}
		if($i==0) echo 'File not found';
	}
	private function findCatName($catId)
	{
		if($catId==1)
		{
			return "Cần bán";
		}elseif($catId==2)
		{
			return "Cho thuê";
		}
		return "";
	}
	/*---------------------Ket thuc Xem 1 ban ghi--------------------------*/
	/*---------------------Bat dau Xem 1 ban ghi--------------------------*/
	public function viewOne()
	{
		if(isset($_POST['id']))
			$id =(int)$_POST['id'] ; // get use_id
		else $id=-1;
		$start=0;
		$limit=1;
		$sidx='';
		$sord='';
		$where="id =$id";
		$select = "id,title, createddate, img1, img2,img3, img4,img5,img6, img7,img8, img9,img10,img11,img12, description,typeid,price,lat,lng";
		$result = $this->Place_model->fetch($select, $where, $sidx, $sord, $start, $limit);
		$i=0;
		
		foreach($result as $userArray)
		{
			$responce->rows[$i]['id']=$userArray->id;
			$responce->rows[$i]['tieude']=$userArray->title;
			$responce->rows[$i]['lat']=$userArray->lat;
			$responce->rows[$i]['lng']=$userArray->lng;
			//$responce->rows[$i]['ngaydang']=date("d/m/Y",$userArray->createddate);
			$responce->rows[$i]['img1']=$userArray->img1;
			$responce->rows[$i]['img2']=$userArray->img2;
			$responce->rows[$i]['img3']=$userArray->img3;
			$responce->rows[$i]['img4']=$userArray->img4;
			$responce->rows[$i]['img5']=$userArray->img5;
			$responce->rows[$i]['img5']=$userArray->img5;
			$responce->rows[$i]['img6']=$userArray->img6;
			$responce->rows[$i]['img7']=$userArray->img7;
			$responce->rows[$i]['img8']=$userArray->img8;
			$responce->rows[$i]['img9']=$userArray->img9;
			$responce->rows[$i]['img10']=$userArray->img10;
			$responce->rows[$i]['img11']=$userArray->img11;
			$responce->rows[$i]['img12']=$userArray->img12;
			$responce->rows[$i]['mota']=$userArray->description;
			$responce->rows[$i]['loai']=$userArray->typeid;
			$responce->rows[$i]['gia']=number_format($userArray->price,0);
			$i++;
			echo json_encode($responce);
		}
		if($i==0) echo 'File not found';
	}
	/*---------------------Ket thuc Xem 1 ban ghi--------------------------*/
	private function add()
	{
		$price=$this->input->post('Price');
		$price=str_replace(",","",$price);
		$user_id=$this->session->userdata('sessionId');
		$dataAdd = array(
				'lat'      		=>      trim(strtolower($this->filter->injection_html($this->input->post('Lat')))),
				'lng'      		=>      trim($this->filter->injection_html($this->input->post('Lng'))),
				'title'    		=>      trim($this->filter->injection_html($this->input->post('Title'))),
				'createddate'   =>      date("Y-m-d H:i:s"),
				'img1'     		=>      trim($this->filter->injection_html($this->input->post('Img1'))),
				'img2'      	=>      trim($this->filter->injection_html($this->input->post('Img2'))),
				'img3'      	=>      trim($this->filter->injection_html($this->input->post('Img3'))),
				'img4'          =>      trim($this->filter->injection_html($this->input->post('Img4'))),
				'img5'       	=>      trim($this->filter->injection_html($this->input->post('Img5'))),
				'description'   =>      trim($this->filter->injection_html($this->input->post('Description'))),
				'price'         =>      $price,
				'typeid'     	=>      trim($this->filter->injection_html($this->input->post('houseType'))),
				'user_id'       =>      $user_id
				
		);
		 if($this->Place_model->add($dataAdd))
		 {
			$responce->status=session_id();
			$responce->ret='success';
		 	echo json_encode($responce);
		 }else
		 {
		 	$responce->status=session_id();
			$responce->ret='failure';
		 	echo json_encode($responce);
		 }	   
	}
	private function addExtra()
	{
		/*
		 * act	add
			diachi	
			dientich	
			donvitinh	0
			duongrong	
			giatien	
			key	iIf2bTc8
			loaitaisan	
			mota	
			nhucau	
			phaply	
			phongkhac	
			phongkhach	
			phongngu	
			phongtam	
			phuonghuong	
			phuongxa	
			quanhuyen	
			session	true
			sotang	
			thanhpho	
			tieude	
			trongtoanha	
			tuyenduong	
			vitritang
		 */
		
		
		$price=$this->input->post('giatien');
		$price=str_replace(",","",$price);
		$user_id=$this->session->userdata('sessionId');
		$dataAdd = array(
				'lat'      		=>      trim(strtolower($this->filter->injection_html($this->input->post('Lat')))),
				'lng'      		=>      trim($this->filter->injection_html($this->input->post('Lng'))),
				'title'    		=>      trim($this->filter->injection_html($this->input->post('tieude'))),
				'createddate'   =>      date("Y-m-d H:i:s"),
				'img1'     		=>      trim($this->filter->injection_html($this->input->post('Img1'))),
				'img2'      	=>      trim($this->filter->injection_html($this->input->post('Img2'))),
				'img3'      	=>      trim($this->filter->injection_html($this->input->post('Img3'))),
				'img4'          =>      trim($this->filter->injection_html($this->input->post('Img4'))),
				'img5'       	=>      trim($this->filter->injection_html($this->input->post('Img5'))),
				'img6'     		=>      trim($this->filter->injection_html($this->input->post('Img6'))),
				'img7'      	=>      trim($this->filter->injection_html($this->input->post('Img7'))),
				'img8'      	=>      trim($this->filter->injection_html($this->input->post('Img8'))),
				'img9'          =>      trim($this->filter->injection_html($this->input->post('Img9'))),
				'img10'       	=>      trim($this->filter->injection_html($this->input->post('Img10'))),
				'img11'          =>     trim($this->filter->injection_html($this->input->post('Img11'))),
				'img12'       	=>      trim($this->filter->injection_html($this->input->post('Img12'))),
				'description'   =>      trim($this->filter->injection_html($this->input->post('mota'))),
				'price'         =>      $price,
				'typeid'     	=>      trim($this->filter->injection_html($this->input->post('loaitaisan'))),
				'user_id'       =>      $user_id,
				'districtid'    =>   	trim($this->filter->injection_html($this->input->post('quanhuyen'))),
				'catid'       	=>   	trim($this->filter->injection_html($this->input->post('nhucau'))),
				'directionid'   =>   	trim($this->filter->injection_html($this->input->post('phuonghuong'))),
				'floornum'   		=>   	trim($this->filter->injection_html($this->input->post('sotang'))),
				'landusecertificate'   		=>   	trim($this->filter->injection_html($this->input->post('phaply'))),
				'sqft'   		=>   	trim($this->filter->injection_html($this->input->post('dientich'))),
				'frontage'   		=>   	0,//Mat tien
				'roomnum'   		=>   	trim($this->filter->injection_html($this->input->post('phongkhach')))
				
		);
		if($this->Place_model->add($dataAdd))
		{
			$responce->status=session_id();
			$responce->ret='success';
			echo json_encode($responce);
		}else
		{
			$responce->status=session_id();
			$responce->ret='failure';
			echo json_encode($responce);
		}
	}
	/**
	 * Upload Image
	 */
	private function upload()
	{
		$uploaddir = './themes/home/uploads/'; 
		$date = new DateTime();		
		$fileName = $date->format('U') .  basename($_FILES['uploadfile']['name']);				
		$file = $uploaddir . $fileName ; 
		if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) 
		{ 
		  echo $fileName; 
		} else {
			echo "error";
		}
	}
	/*-----------------------Bat dau xu ly thong tin: them sua xoa...-------------*/
	public function process()
	{
		$act=$this->filter->injection_html($this->input->post('act'));
		switch ($act) 
		{
		    case "add"://add
		        $this->add();
		        break;
		        case "addExtra"://add
		        	$this->addExtra();
		        	break;
		        
		     case "upload"://upload image
		        $this->upload();
		        break;		
		     default:
		     	echo md5('No process');
		}
	}
	/*-----------------------Ket thuc xu ly thong tin: them sua xoa...-------------*/
	
	
}
